﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimplePlanner.Entity;

namespace SimplePlanner.Logic
{
    public class SchedulingService
    {
        public List<Subject> subs; // Subject
        public List<Solution> res; // Array of Solution: Returns here
        private List<Index> okIndex; // indexes
        private List<Period> TB;// Array of Period

        public void plan()
        {
            dfs(0);
        }

        private void dfs(int x)
        {
            if (x == subs.Count)
            {
                Solution plan = new Solution();
                for (int i = 0; i < okIndex.Count; i++)
                    plan.addIndex( (Index) okIndex[i] );
                res.Add(plan);

                return;
            }
            Subject s = (Subject)subs[x];
            List<Index> indices = s.indexes; // Array of Index

            // foreach index in subject subs[x]
            for (int i = 0; i < indices.Count; i++)
            {
                // enum index
                bool indexCan = true;
                Index index = (Index) indices[i];
                List<Period> periods = index.periods;

                // for each period in current index
                for (int j = 0; j < periods.Count; j++)
                {
                    Period period = (Period) periods[j];

                    bool clashWithTB = false;
                    // check whether clash with current timetable
                    for (int k = 0; k < TB.Count; k++)
                        if (Period.overlap( period, (Period) TB[k]) )
                        {
                            clashWithTB = true;
                            break;
                        }
                    // end check

                    if (clashWithTB)
                    {
                        indexCan = false;
                        break;
                    }
                }

                if (indexCan)
                {
                    // add index to res
                    okIndex.Add(index);
                    for (int j = 0; j < periods.Count; j++)
                        TB.Add( (Period) periods[j]);
                    // end

                    dfs(x + 1);

                    // remove
                    okIndex.Remove(index);
                    for (int j = 0; j < periods.Count; j++)
                        TB.RemoveAt( TB.Count - 1);
                }
            }        
        }
    }
}
